package com.example.myapplication.utils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexAbstract {
    public static Set<String> getApi(String s){
        String pattern = "\"tool_name\": \"(.*)\"";
        Pattern r= Pattern.compile(pattern);
        Matcher m=r.matcher(s);
        Set<String> ans=new HashSet<>();
        while (m.find()){
            ans.add(decode( m.group(1)).trim());
        }
        return ans;
    }
    public static String getContent(String s){
        String pattern = "\"content\": \"(.*)\"";
        Pattern r= Pattern.compile(pattern);
        Matcher m=r.matcher(s);
        String ans=null;
        while (m.find()){
            ans=m.group(1);
        }
        String pattern1="\\\\\"final_answer\\\\\":\\s*\\\\\"(.*?)\\\\\"";
        r=Pattern.compile(pattern1);
        m=r.matcher(s);
        if(m.find()){
            ans=m.group(1);
        }
        String pattern2 = "\"final_answer\": \"(.*)\"";
        r= Pattern.compile(pattern2);
        m=r.matcher(s);
        while (m.find()){
            ans=m.group(1);
        }
        ans=ans==null?"求解失败":ans;
        return decode(ans).trim().replace("\\n","\n").replace("\\\"","\"");
    }
    public static String decode(String unicodeStr) {
        if (unicodeStr == null) {
            return null;
        }
        int len = unicodeStr.length();
        StringBuilder str = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = unicodeStr.charAt(i);
            if (c == '\\' && i + 1 < len && unicodeStr.charAt(i + 1) == 'u') {
                int codePoint = 0;
                boolean valid = true;
                for (int j = 0; j < 4 && valid && i + 2 + j < len; j++) {
                    char uc = unicodeStr.charAt(i + 2 + j);
                    int digit = Character.digit(uc, 16);
                    if (digit == -1) {
                        valid = false;
                    } else {
                        codePoint = codePoint * 16 + digit;
                    }
                }
                if (valid) {
                    str.append((char) codePoint);
                    i += 5;
                } else {
                    str.append(c);
                }
            } else {
                str.append(c);
            }
        }
        return str.toString();
    }
}
